package com.cobo.fitness.web.post.services.impl;
import com.cobo.fitness.web.post.entity.PostMeta;
import com.cobo.fitness.web.post.services.TagService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cobo.fitness.web.post.entity.Tag;
import com.cobo.fitness.web.post.mapper.TagMapper;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class TagServiceImpl  extends ServiceImpl<TagMapper, Tag> implements TagService {

    @Override
    public List<Tag> saveOrUpdateTag(String[] tags) {
        List<Tag> existTags = lambdaQuery()
                .in(Tag::getName, Lists.newArrayList(tags))
                .list();
        Map<String, List<Tag>> filterMap = existTags.stream().collect(Collectors.groupingBy(Tag::getName));

        List<Tag> transTag = new ArrayList<>();
        for (String tag : tags) {
            if (filterMap.containsKey(tag)) {
                transTag.add(filterMap.get(tag).get(0));
            }else {
                Tag item = new Tag();
                item.setName(tag);
                save(item);
                transTag.add(item);
            }
        }
        return transTag;
    }
}